package com.qf.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 常肖飞先生
 * @version V1.0
 * @Project day41_1
 * @Package ${PACKAGE_NAME}
 * @Description: ${TODO}
 * @Date 2022/5/11 10:13
 */
@WebServlet(name = "CookieServlet",urlPatterns = "/cookie")
public class CookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        createCookie(request,response,"uname","tom",2000);
    }

    private void createCookie(HttpServletRequest request,HttpServletResponse response,String key,String value,int lifeTime)throws IOException{
        //服务器端生成cookie  步骤
        //创建cookie
        Cookie cookie = new Cookie(key, value);
        //设置有效期
        // -1: 代表内存级别（浏览器窗口关闭，数据删除）
        // 0 : 删除当前数据。设置数据立即失效，删除指定的key的cookie。
        // >0: 设置浏览器端 cookie的保存的时长，单位是秒
        cookie.setMaxAge(lifeTime);
        //设置cookie的保存路径. 获取当前项目的上下文路径。/day41
        cookie.setPath(request.getContextPath());
        //设置 http协议只读
        cookie.setHttpOnly(true);
        //返回前端
        response.addCookie(cookie);

        response.getWriter().println("hello");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
